<template>
  <n-modal
    v-model:show="modalVisible"
    class="w-360px"
    preset="card"
    title="修改密码"
    :auto-focus="false"
    :bordered="true"
    :mask-closable="false"
    :close-on-esc="false"
    :on-after-leave="resetFormValue"
  >
    <n-form ref="formRef" :model="formValue" :rules="rules" @submit="handleSubmit">
      <n-form-item label="手机号">
        <n-input :value="formValue.phone" disabled />
      </n-form-item>
      <n-form-item label="旧密码" path="password">
        <n-input
          v-model:value="formValue.password"
          type="password"
          show-password-on="click"
          autofocus
          clearable
          placeholder="输入旧密码"
        />
      </n-form-item>
      <n-form-item label="新密码" path="newPassword">
        <n-input
          v-model:value="formValue.newPassword"
          type="password"
          :input-props="{ autocomplete: 'new-password' }"
          show-password-on="click"
          clearable
          placeholder="输入新密码"
        />
      </n-form-item>
      <n-row :gutter="[0, 24]">
        <n-col :span="24" class="flex justify-end">
          <n-button type="primary" attr-type="submit" :loading="btnStatus" :disabled="btnStatus">确认</n-button>
        </n-col>
      </n-row>
    </n-form>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import type { FormInst } from 'naive-ui';
import { fetchChangePassword } from '@/service';
import { formRules } from '@/utils';

export interface Props {
  /** 弹窗可见性 */
  visible: boolean;
  /** 用户ID */
  userId: string;
  /** 手机号 */
  phone: string;
}
const btnStatus = ref(false);
const props = defineProps<Props>();
interface Emits {
  (e: 'update:visible', visible: boolean): void;
}
const emit = defineEmits<Emits>();
const modalVisible = computed({
  get() {
    return props.visible;
  },
  set(visible) {
    emit('update:visible', visible);
  }
});
const closeModal = () => {
  modalVisible.value = false;
};

const formRef = ref<FormInst | null>(null);
const formInitValue = {
  phone: props.phone,
  password: '',
  newPassword: ''
};
const formValue: any = ref({ ...formInitValue });
const rules = {
  password: formRules.pwd,
  newPassword: formRules.pwd
};

function resetFormValue() {
  formValue.value = { ...formInitValue };
  btnStatus.value = false;
}

function handleSubmit(e: any) {
  e.preventDefault();
  formRef.value
    ?.validate(async errors => {
      if (!errors) {
        const { data } = await fetchChangePassword(props.userId, formValue.value.password, formValue.value.newPassword);
        if (data) {
          window.$message?.success('密码修改成功');
          resetFormValue();
          closeModal();
        }
      }
    })
    .catch(() => {
      window.$message?.error('密码修改失败');
    });
}
</script>
